//
//  SampuxReminderView.m
//  Sampux
//
//  Created by rzm on 16/7/5.
//  Copyright © 2016年 rzm. All rights reserved.
//

#import "SampuxReminderView.h"
#import "IsValidateOrNot.h"
#import "SampuxCustomTextFiledView.h"
#import "SampuxValidationCodeView.h"
#import "SPDeleteTextFiledView.h"

@interface SampuxReminderView ()<UITextFieldDelegate>
{
    NSInteger _countDownTime;
    NSTimer *_timer ;
    CGFloat font;
}
@property (nonatomic, strong) UITextField *phoneF ;
//@property (nonatomic, strong) UIView *codeBackView ;
@property (nonatomic, strong) UIButton *codeBtn ;
@property (nonatomic, strong) UITextField *codeF ;
@property (nonatomic, strong) SPDeleteTextFiledView *phoneView;
@property (nonatomic, strong) SampuxValidationCodeView *codeView;
@property(nonatomic,assign) BOOL isConnectOrNot;

@end
@implementation SampuxReminderView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.isConnectOrNot = YES;
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reminderGetCode:) name:NOTIFICATION_RESPONSE_FORGETPWD_VEGISTER object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(verifyReminderCode:) name:NOTIFICATION_RESPONSE_FORGETPWD_VERIFY object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(connectSuccess) name:@"socketConnectSuccess" object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(connectFail) name:@"socketConnectFail" object:nil];
        [self loadUI];
    }
    return self;
}

- (void)connectSuccess
{
    self.isConnectOrNot = YES;
}

- (void)connectFail
{
    self.isConnectOrNot = NO;
}

- (void)loadUI
{
    CGFloat font = 8;
    if (IS_IPHONE_4_OR_LESS) {
        font = 14.;
    }else if (IS_IPHONE_5_OR_LESS)
    {
        font = 14.;
    }else if (IS_IPHONE_6)
    {
        font = 16.;
    }else
    {
        font = 17.;
    }
    
    UIView *remindrView = [[UIView alloc]initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight - 64)];
    [self addSubview:remindrView];
    
    CGFloat spaceX = self.width/2 - Sampux6WScale(250)/2;
    UIButton *iconImageView = [UIButton createButtonWithImage:imageNamed(@"sampux_logo")];
    iconImageView.frame = CGRectMake(0, remindrView.height * 0.08, remindrView.width, remindrView.height *0.15);
    [remindrView addSubview:iconImageView];
    iconImageView.userInteractionEnabled = NO;
    
    CGRect phoneRect = CGRectMake(spaceX, iconImageView.bottom + Sampux6HScale(30), Sampux6WScale(SampuxCustomW), Sampux6HScale(SampuxCustomH));
    _phoneView = [[SPDeleteTextFiledView alloc]initWithFrame:phoneRect];
    [_phoneView createDeleteTextFiledWithPlaceholder:@"输入手机号" andLeftImage:@"make-user" andRightImage:@"delete"];
    [remindrView addSubview:_phoneView];
    _phoneView.textFiled.delegate = self;
//    _phoneF = [UITextField createTextFieldWithRect:phoneRect andPlaceholder:@"请输入手机号或邮箱" andLeftImage:@"user"];//
//    _phoneF.delegate = self;
//    [remindrView addSubview:_phoneF];
    
    _codeView = [[SampuxValidationCodeView alloc]initWithFrame:CGRectMake(spaceX, _phoneView.bottom+ SampuxMargin,  Sampux6WScale(SampuxCustomW), Sampux6HScale(SampuxCustomH))];
    [_codeView createValidationCodeWithPlaceholder:@"输入验证码" andLeftImage:@"feedBackCode" andRightImage:@"eye" andcodeBtn:@"获取验证码"];
    _codeView.codeF.delegate = self;
    [_codeView.codeBtn addTarget:self action:@selector(sendCode) forControlEvents:UIControlEventTouchUpInside];
//    [_codeView.eyeBtn addTarget:self action:@selector(showPassWord) forControlEvents:UIControlEventTouchUpInside];
    _codeView.codeF.secureTextEntry = YES;
    [remindrView addSubview:_codeView];
//    UIView *codeBackView = [[UIView alloc]initWithFrame:CGRectMake(spaceX, _phoneView.bottom+ SampuxMargin,  Sampux6WScale(SampuxCustomW), Sampux6HScale(SampuxCustomH))];
//    [remindrView addSubview:codeBackView];
////    codeBackView.layer.borderWidth = 1;
////    codeBackView.layer.borderColor = THMainTextKColor.CGColor;
//    self.codeBackView = codeBackView;
//    codeBackView.backgroundColor = THSystemWhiteColor;
//    [UIView createLineViewInbottom:codeBackView];
//    
//    _codeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    _codeBtn.titleLabel.font = THFont(14);
//    _codeBtn.frame = CGRectMake(codeBackView.width - Sampux6WScale(7) - Sampux6WScale(80), Sampux6HScale(7), Sampux6WScale(80), codeBackView.height - Sampux6HScale(14));
//    [_codeBtn addTarget:self action:@selector(sendCode) forControlEvents:UIControlEventTouchUpInside];
//    _codeBtn.backgroundColor = THCodeBlueColor;
//    [codeBackView addSubview:_codeBtn];
//    _codeBtn.titleLabel.textAlignment = NSTextAlignmentRight;
//    self.codeBtn = _codeBtn;
//    _codeBtn.titleLabel.font = THFont(font);
//    [_codeBtn setCorner:5];
//    [_codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
//    
//    _codeF = [UITextField createTextFieldWithRect:CGRectMake(0, 0,codeBackView.width - 10 - _codeBtn.width -10, codeBackView.height) andPlaceholder: @"请输入验证码" andLeftImage:@"code"];
//    [codeBackView addSubview:_codeF];
//    _codeF.delegate = self;
    
    UIButton *nextStepBtn = [UIButton createButtonWithTitle:@"下一步" buttonType:UIButtonTypeCustom frame:CGRectMake(self.width/2 -  Sampux6WScale(354/2)/2, CGRectGetMaxY(_codeView.frame) + Sampux6HScale(30), Sampux6WScale(354/2),  Sampux6HScale(SampuxCustomH)) titleFont:THFont(font) titleColor:THDeFaultBlueColor backColor:THSystemClearColor];
    nextStepBtn.layer.borderWidth = 1;
    nextStepBtn.layer.borderColor = THWhiteAlplaColor(0.6).CGColor;
    [remindrView addSubview:nextStepBtn];
    [nextStepBtn setCorner:nextStepBtn.height/2];
    [nextStepBtn addTarget:self action:@selector(nextStepClick) forControlEvents:UIControlEventTouchUpInside];
}

//- (void)showPassWord
//{
//    if (_codeView.eyeBtn.selected == YES) {
//        _codeView.codeF.secureTextEntry = NO;
//        
//    }else
//    {
//        _codeView.codeF.secureTextEntry = YES;
//        
//    }
//}

- (void)sendCode
{
    BOOL isMobile = [IsValidateOrNot isValidateMobile:self.phoneView.textFiled.text];
    BOOL isEmail = [IsValidateOrNot isValidateEmail:self.phoneView.textFiled.text];
    
    if ([self.phoneView.textFiled.text isEqualToString: @""] ||self.phoneView.textFiled.text.length == 0){
        [SVProgressHUD showErrorWithStatus:@"用户名必须为手机号"];
//        [MBProgressHUD showError:@"用户名必须为手机号或者邮箱"];
    }else
    {
        if (!isMobile&&!isEmail)
        {
            [SVProgressHUD showErrorWithStatus:@"用户名必须为手机号"];
//            [MBProgressHUD showError:@"用户名必须为手机号或者邮箱"];
        } else {
            if (self.isConnectOrNot == NO) {
                [SVProgressHUD showErrorWithStatus:@"网络未连接，请检查您的网络连接设置"];
            } else {
                _countDownTime = 60;
                self.codeBtn.userInteractionEnabled = NO;
                //调用后台连接，获取验证码
                [GBInterMaster_CommForSystem requestUserForgetPwdVegister:0 withAccount:self.phoneView.textFiled.text];
            }
        }
    }
}

//*忘记密码（验证校验码）
- (void)nextStepClick
{
    BOOL isMobile = [IsValidateOrNot isValidateMobile:self.phoneView.textFiled.text];
    BOOL isEmail = [IsValidateOrNot isValidateEmail:self.phoneView.textFiled.text];

    if (isEmail == YES||isMobile == YES) {
        if (self.isConnectOrNot == NO) {
            [SVProgressHUD showErrorWithStatus:@"网络未连接，请检查您的网络连接设置"];
        } else {
            [GBInterMaster_CommForSystem requestUserForgetPwdVerify:0 withCheckCode:self.codeView.codeF.text];
        }
    } else {
        [SVProgressHUD showErrorWithStatus:@"用户名错误"];
//        [MBProgressHUD showError:@"用户名错误"];
    }
}

//需要封装
/**
 *  创建定时器
 */
- (void)createTimer
{
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeCountDown) userInfo:nil repeats:YES];
    [_timer setFireDate:[NSDate distantPast]];
}
/**
 *  定时器减到0
 */
- (void)timeCountDown
{
    if (_countDownTime == 1) {
        [self.codeView.codeBtn setTitle:@"重新发送" forState:UIControlStateNormal];
        self.codeView.codeBtn.userInteractionEnabled = YES;
        [_timer invalidate];
        _timer = nil;
    } else {
        _countDownTime--;
        NSString *timeStr = [NSString stringWithFormat:@"重新发送%.2d",_countDownTime];
        [self.codeView.codeBtn setTitle:timeStr forState:UIControlStateNormal];
        self.codeView.codeBtn.userInteractionEnabled = NO;
    }
}

- (void)reminderGetCode:(NSNotification *)notification
{
    id userInfo = [notification userInfo];
    if(userInfo == nil){
        return;
    }
    NSDictionary * result = userInfo;
    int msgNumber = [[result objectForKey:@"msgNumber"] intValue];
    int responseCode = [[result objectForKey:@"responseCode"] intValue];
    NSLog(@"reminderGetCode == 结果，消息序号：%d，响应码：%x",msgNumber,responseCode);
    if(responseCode == 0x00){
        dispatch_async(dispatch_get_main_queue(), ^{
            [self createTimer];
        });
    } else {
        [SVProgressHUD showErrorWithStatus:[SPResponseCodePrompt responseCodePrompt:responseCode]];
//        [MBProgressHUD showError:[SPResponseCodePrompt responseCodePrompt:responseCode]];
    }
}

- (void)verifyReminderCode:(NSNotification *)notification
{
    id userInfo = [notification userInfo];
    if(userInfo == nil){
        return;
    }
    NSDictionary * result = userInfo;
    int msgNumber = [[result objectForKey:@"msgNumber"] intValue];
    int responseCode = [[result objectForKey:@"responseCode"] intValue];
    NSLog(@"verifyReminderCode == 结果，消息序号：%d，响应码：%x",msgNumber,responseCode);
    if(responseCode == 0x00){
        if ( self.nextStepClickDelegate &&[self.nextStepClickDelegate respondsToSelector:@selector(remindViewNextStepBtnClick)])
        {
            [self.nextStepClickDelegate remindViewNextStepBtnClick];
        }
    } else {
        [SVProgressHUD showErrorWithStatus:[SPResponseCodePrompt responseCodePrompt:responseCode]];
//        [MBProgressHUD showError:[SPResponseCodePrompt responseCodePrompt:responseCode]];
    }
}


#pragma -mark 输入框代理
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    [self layoutIfNeeded];
    self.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight );
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self layoutIfNeeded];
    CGFloat keyboardHeight = 216.0f;
    self.frame = CGRectMake(0, -keyboardHeight/6 , self.width, kScreenHeight);
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [self layoutIfNeeded];
    self.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == _codeView.codeF) {
        NSString * toBeString = [_codeView.codeF.text stringByReplacingCharactersInRange:range withString:string];
        if (toBeString.length > 6 && range.length!=1){
            textField.text = [toBeString substringToIndex:6];
            return NO;
        }
        return YES;
    }else
    {
        return YES;
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    self.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight );
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}

- (void)dealloc{
    if (_timer.isValid) {
        [_timer invalidate];
        _timer = nil;
    }
    [_timer invalidate];
    _timer = nil;
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
@end
